
/*
 * @项目名称: 模板开发
 * @FilePath: /meek/src/components/utils/selecthole.js
 * @Author: 
 * @Date: 2020-01-02T15:34:56+08:00
 * @LastEditors: 
 * @LastEditTime: 2021-05-08T10:48:39+08:00
 * Copyright (c) 2018-2022 
 */
                                                    
import Polygon from '../../geometry/polygon'
import FillStyle from '../../style/fillstyle'
import LineStyle from '../../style/linestyle'
import Feature from '../../meek/feature'
import { polygonContainsLinestring } from "../../geometry/analysis/contains"

/**
 * 复制多边形的内环到一个多边形中，以显示选中高亮效果
 * 
 * @method cloneHoleToFeature
 * @param feature {Feature}
 * @param coords {Array}
 * @return {Array}
 */
export function cloneHoleToFeature(feature, coords) {
  let geometry = new Polygon()
  geometry.setCoordinates(coords)
  let holeFeature = new Feature(geometry, {}, "", newHoleStyle(feature) )
  holeFeature.set("parent", feature)
  return holeFeature;
}

/**
 * 根据原多边形的样式计算环高亮的样式
 * 
 * @method newHoleStyle
 * @param feature {Feature}
 * @return {Array} 
 */
function newHoleStyle(feature) {
  const newStyles = []
  const white = [255, 255, 255]

  const firstStyle = feature.style[1] || feature.style[0]

  const cloneLineStyle1 = firstStyle.borderStyle.clone()
  cloneLineStyle1.width = firstStyle.borderStyle.width
  newStyles.push(new FillStyle(
    white,
    cloneLineStyle1,
    0
  ))

  const cloneLineStyle = firstStyle.borderStyle.clone()
  cloneLineStyle.width = firstStyle.borderStyle.width + 3
  cloneLineStyle.color = white
  cloneLineStyle.lineCap = LineStyle.LineCap.ROUND
  cloneLineStyle.lineJion = LineStyle.LineJion.ROUND

  const cloneStyle = new FillStyle(
    white,
    cloneLineStyle,
    0
  )

  newStyles.unshift(cloneStyle)
  return newStyles;
}

function holeContainsHole(hole1, hole2) {
  const polygon = new Polygon([hole1]);
  return polygonContainsLinestring(polygon, hole2);
}

export function getInnerHoles(holes) {
  let selectedHoles = holes.slice()
  let len = holes.length;
  for (let i = 0; i < len; i++ ) {
    const hole1 = holes[i];
    for (let j = 0; j < len; j++) {
      if (i === j) {
        continue;
      }

      const hole2 = holes[j];

      if (holeContainsHole(hole1, hole2)) {
        selectedHoles = selectedHoles.filter(hole => hole !== hole1)
      }
    }
  }
  return selectedHoles;
}

export default {
  cloneHoleToFeature,
  getInnerHoles
}
